import 'package:flutter_reactive_value/flutter_reactive_value.dart';
import 'persona_entity.dart';

/// 用户会话控制器
class PersonaSessionController {
  static final PersonaSessionController _instance =
      PersonaSessionController._();
  static PersonaSessionController get globalInstance => _instance;

  PersonaSessionController._() {
    _userList.addAll(PersonaEntity.getDefaultKiteUsers());
  }

  /// 用户数据列表
  final List<PersonaEntity> _userList = [];

  /// 当前用户状态
  final ReactiveValueNotifier<PersonaEntity?> _currentUser =
      ReactiveValueNotifier<PersonaEntity?>(null);

  ReactiveValueNotifier<PersonaEntity?> get currentPersonaState => _currentUser;

  /// 登录
  bool login(String account, String password) {
    final user = _userList.firstWhere(
      (u) => u.credentialAccount == account && u.accessSecret == password,
      orElse: () => PersonaEntity.createEmptyInstance(),
    );

    if (user.uniqueIdentifier.isNotEmpty) {
      _currentUser.value = user;
      return true;
    }
    return false;
  }

  /// 注册
  bool register(String account, String password, String displayName) {
    // 检查账号是否已存在
    final exists = _userList.any((u) => u.credentialAccount == account);
    if (exists) return false;

    // 创建新用户
    final newUser = PersonaEntity(
      uniqueIdentifier: 'user_${DateTime.now().millisecondsSinceEpoch}',
      credentialAccount: account,
      accessSecret: password,
      displayAlias: displayName,
      avatarResourceUrl: 'assets/images/avatar1.png',
      personalizedBio: 'New member of Kudos!',
    );

    _userList.add(newUser);
    _currentUser.value = newUser; // 自动登录
    return true;
  }

  /// 退出登录
  void logout() {
    _currentUser.value = null;
  }

  /// 更新用户信息
  bool updateUserInfo({String? displayName, String? avatarUrl, String? bio}) {
    final currentUser = _currentUser.value;
    if (currentUser == null) return false;

    // 创建更新后的用户实体
    final updatedUser = currentUser.duplicateWithModifications(
      displayAlias: displayName,
      avatarResourceUrl: avatarUrl,
      personalizedBio: bio,
    );

    // 更新当前用户状态
    _currentUser.value = updatedUser;

    // 同时更新用户列表中的数据
    final userIndex = _userList.indexWhere(
      (u) => u.uniqueIdentifier == currentUser.uniqueIdentifier,
    );
    if (userIndex != -1) {
      _userList[userIndex] = updatedUser;
    }

    return true;
  }

  /// 静态方法：快速登录
  static bool quickLogin(String account, String password) {
    return globalInstance.login(account, password);
  }

  /// 静态方法：快速注册
  static bool quickRegister(
    String account,
    String password,
    String displayName,
  ) {
    return globalInstance.register(account, password, displayName);
  }

  /// 静态方法：快速退出
  static void quickLogout() {
    globalInstance.logout();
  }

  /// 根据用户ID获取用户信息
  PersonaEntity? getUserById(String userId) {
    try {
      return _userList.firstWhere((user) => user.uniqueIdentifier == userId);
    } catch (e) {
      return null;
    }
  }

  /// 静态方法：快速更新用户信息
  static bool quickUpdateProfile({
    String? displayName,
    String? avatarUrl,
    String? bio,
  }) {
    return globalInstance.updateUserInfo(
      displayName: displayName,
      avatarUrl: avatarUrl,
      bio: bio,
    );
  }

  /// 静态方法：快速获取用户信息
  static PersonaEntity? quickGetUserById(String userId) {
    return globalInstance.getUserById(userId);
  }
}
